<script setup>
import {login} from "@/apis/v1/user/login.js";
import {useRouter} from "vue-router";
import {ElMessage} from "element-plus";
import {useTokenStore, useUserStore} from "@/store/user.js";
import {User, Lock} from "@element-plus/icons-vue";

const router = useRouter();
const isLogin = ref(false);
const user = ref({
  username: "",
  password: "",
});
const rules = ref({
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 5, max: 12, message: '用户名长度应为5到12', trigger: 'blur'},
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 16, message: '密码长度应为6到16', trigger: 'blur'},
  ],
});
const goForget = (data) => {
  ElMessage.error("密码找回请联系客服");
};
const signIn = () => {
  isLogin.value = true;
  login(user.value).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
    } else {
      const useToken = useTokenStore();
      const userStore = useUserStore();
      useToken.setToken(res.result.token);
      userStore.setUser(res.result.userInfo);
      ElMessage.success("登录成功");
      setTimeout(() => {
        // 跳转首页
        router.push("/");
      }, 1000);
    }
  });
  isLogin.value = false;
};
</script>

<template>
  <div class="content myCenter">
    <h1>账号密码登录</h1>
    <form style="width: 300px;">
      <el-form :model="user" class="demo-ruleForm" label-width="65px"
               label-position="left" style="max-width: 300px" :rules="rules">
        <el-form-item label="用户名" prop="username" required>
          <el-input clearable placeholder="请输入用户名" v-model="user.username"
                    :prefix-icon="User"/>
        </el-form-item>
        <el-form-item label="密码" prop="password" required>
          <el-input placeholder="请输入密码" v-model="user.password" type="password" autocomplete="off"
                    show-password :prefix-icon="Lock"/>
        </el-form-item>
        <div style="width: 300px; height: 30px; margin-bottom: 20px" class="myCenter">
          <a class="a" style="margin: 0; color: #ff416c" href="#" @click="goForget('邮箱验证码')">忘记密码</a>
        </div>
        <div style="width: 300px; height: 30px;" class="myCenter">
          <button :disabled="isLogin" @click="signIn" type="button">登录</button>
        </div>
      </el-form>
    </form>
  </div>
</template>

<style scoped lang="less">
.content {
  width: 50%;
  height: 100%;
  border-radius: 10px 0 0 10px;
  background: var(--background);
  flex-direction: column;
  opacity: .9;

  h1 {
    color: var(--fontColor);
    margin-bottom: 20px;
  }

  button {
    border-radius: 2rem;
    border: 1px solid var(--white);
    background: var(--gradualRed);
    color: var(--white);
    font-size: 16px;
    font-weight: bold;
    padding: 12px 45px;
    letter-spacing: 2px;
    cursor: pointer;

    &:hover {
      transition: all 0.5s ease-in-out;
      transform: scale(1.2);
    }
  }

  .demo-form-inline .el-input {
    --el-input-width: 220px;
  }
}
</style>